package com.hema.auction.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.hema.auction.R;
import com.hema.auction.adapter.SelectImgAdapter;
import com.hema.auction.base.BasePhotoActivity;
import com.hema.auction.bean.GoodsInfo;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.GlideUtils;
import com.hema.auction.utils.Utils;
import com.hema.auction.widget.view.TitleView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.hema.auction.R.id.iv_img;

/**
 * 描述:发布晒单
 * 作者:john
 */
public class PulishSunActivity extends BasePhotoActivity {

    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(iv_img)
    ImageView ivImg;
    @BindView(R.id.tv_market_price)
    TextView tvMarketPrice;
    @BindView(R.id.tv_shopping_coin)
    TextView tvShoppingCoin;
    @BindView(R.id.tv_dealer)
    TextView tvDealer;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_publish)
    TextView tvPublish;
    @BindView(R.id.tv_date)
    TextView tvDate;

    private GoodsInfo info;

    private SelectImgAdapter adapter;
    private List<LocalMedia> imgs = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pulish_sun);
        info = getIntent().getParcelableExtra(Constant.EXTRA_GOOD_INFO);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        tvDate.setText(Utils.timedate(info.getFinalTime()));
        GlideUtils.load(this, info.getImg(), ivImg);
        tvMarketPrice.setText(Utils.priceUnitFormat(this, info.getPrice()));
        tvDealer.setText(info.getOwnerName());
        tvShoppingCoin.setText(Utils.priceUnitFormat(this, info.getFinalPrice()));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new SelectImgAdapter(imgs);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_del:
                        imgs.remove(position);
                        adapter.notifyDataSetChanged();
                        break;
                    case R.id.iv_img:
                        PictureSelector.create(PulishSunActivity.this).externalPicturePreview(position, adapter.getData());
                        break;
                }
            }
        });

    }

    @OnClick({R.id.tv_publish, R.id.iv_add})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_publish:
                if (etContent.getText().toString().trim().length() == 0) {
                    showToastSafe(R.string.publish_content_empty);
                } else if (adapter.getData().size() == 0) {
                    showToastSafe(R.string.publish_img_empty);
                } else {
                    if (adapter.getData().size() > 0) {
                        isAutoDismissDialog = false;
                        showProgressDialog(false);
                        new Thread(imgRun).start();

                    }
                }
                break;
            case R.id.iv_add:
                PictureSelector.create(this).openGallery(PictureMimeType.ofImage()).
                        theme(R.style.my_picture_default_style).maxSelectNum(9).selectionMedia(adapter.getData())
                        .compress(true).compressMode(PictureConfig.LUBAN_COMPRESS_MODE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
        }


    }

    private Runnable imgRun = new Runnable() {
        @Override
        public void run() {
            String data = "";
            for (LocalMedia localMedia : adapter.getData()) {
                try {
                    File file = new File(localMedia.getCompressPath());
                    if (Utils.isEmpty(data))
                        data = Utils.encodeBase64File(file);
                    else
                        data += "," + Utils.encodeBase64File(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            HttpManager.getInstance(PulishSunActivity.this).fileUpload(data, false, PulishSunActivity.this);
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    imgs = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    adapter.setNewData(imgs);
                    break;
            }
        }
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_FILE_UPLOAD:
                try {
                    if (result.getInt("errcode") == 0) {
                        List<String> imgs = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<String>>() {
                        }.getType());
                        if (imgs != null) {
                            String data = "";
                            for (String img : imgs) {
                                if (Utils.isEmpty(data)) {
                                    data = img;
                                } else {
                                    data += "," + img;
                                }
                            }
                            HttpManager.getInstance(this).createOneShow(info.getOrderId(), data, etContent.getText().toString(), this);
                        }
                    } else {
                        showToastSafe(result);
                        dismissProgressDialog();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissProgressDialog();
                }
                break;
            case TAG_CREATE_ONE_SHOW:
                try {
                    if (result.getInt("errcode") == 0) {
                        finish();
                    } else {
                        showToastSafe(result);
                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        switch (httpTag) {
            case TAG_CREATE_ONE_SHOW:
                dismissProgressDialog();
                break;
        }
    }
}
